import socket
import time
from threading import Thread


#
# def countdown(n):
#     while n > 0:
#         print('T-minus', n)
#         n -= 1
#         time.sleep(2)
#
#
# t = Thread(target=countdown, args=(10,))  # 创建线程
#
# # t = Thread(target=countdown, args=(10,),daemon=True)
# #  表示后台进程，到所有线程都终止前仍保持运行
#
# t.start()  # 开启子线程执行
# # t.join()  # 等待子线程停止后，再执行主线程任务
# if t.is_alive():
#     print('Still running')
# else:
#     print('Completed')


# # 后台线程无法等待，如果你需要终止线程，那么这个线程必须通过编程在某个特定点轮询来退出
# class CountdownTask:
#     def __init__(self):
#         self._running = True
#
#     def terminate(self):
#         self._running = False
#
#     def run(self, n):
#         while self._running and n > 0:
#             print('T-minus', n)
#             n -= 1
#             time.sleep(2)
#
#
# # 遇上IO阻塞，通过超时去操作线程
# class IOTask:
#     def terminate(self):
#         self._running = False
#
#     def run(self, sock):
#         sock.settimeout(5)
#         while self._running:
#             try:
#                 data = sock.recv(8192)
#                 break
#             except socket.timeout:
#                 continue
#         return
#
#
# if __name__ == '__main__':
#     c = CountdownTask()
#     t1 = Thread(target=c.run, args=(10,))
#     t1.start()  # 启动线程
#     time.sleep(10)
#     c.terminate()  # 终止线程
#     t1.join()  # 等待子线程结束



# 通过继承的方法实现线程
class CountdownThread(Thread):
    def __init__(self, n):
        super().__init__()
        self.n = n

    def run(self):
        while self.n > 0:
            print('T-minus', self.n)
            self.n -= 1
            time.sleep(5)

if __name__ == '__main__':
    c = CountdownThread(5)
    c.start()
